package com.object;

public class ArrayList<T>{
	int capacity = 30;
	Object[] values = new Object[capacity];
	int writeIndex;
	// [][][][][]	capacity = 5 , writeIndex=0
	// [1][][][][]	capacity = 5 , writeIndex=1
	// [1][2][][][]	capacity = 5 , writeIndex=2
	public void add(T value){
		verifyCapacity(1);
		values[writeIndex] = value;
		writeIndex++; //size
	}
	// [1][2][][][]		capacity = 5 , writeIndex=2
	// [1][2][3][4][]	capacity = 5 , writeIndex=5
	public void add(T[] value){
		verifyCapacity(value.length);
		System.arraycopy(value, 0, values, writeIndex, value.length);
		writeIndex+=value.length; //size
	}
	
	
	public T get(int index){
		if(index >= writeIndex){
			throw new IndexOutOfBoundsException("maxsize="+writeIndex+",get index="+index);
		}
		Object value = values[index];
		if(value == null){
			return null;
		}
		return (T)value;
	}
	public int size(){
		return writeIndex;
	}
	private final void verifyCapacity(int size){
		if(size > capacity - writeIndex){
			expandCapacity((size/capacity+2)*capacity);
		}
	}
	// 扩大容量
	public void expandCapacity(int capacity){
		if(capacity > this.capacity){
			Object[] nvalues = new Object[capacity];
			System.arraycopy(values, 0, nvalues, 0, writeIndex);
			this.capacity = capacity;
			/* 这里是孙凯写的 2017-09-01 19:34:00，拷贝来拷贝去，怎么不再拷贝一次呢
			 * values = new Object[capacity];
			 * System.arraycopy(nvalues, 0, values, 0, writeIndex);
			 */
			this.values = nvalues;
		}
	}
	// 添加 [0][1][2][3][4][5][][][] capacity = 9 , writeIndex=6
	// 删除 [0][1][ ][3][4][5][][][] capacity = 9 , writeIndex=5
	// 结果 [0][1][3][4][5][ ][][][] capacity = 9 , writeIndex=5
	public T remove(int index){
		return null;
	}
	public static void main(String[] args) {
		ArrayList<Integer> l = new ArrayList<Integer>();
		for (int i = 0; i < 1000; i++) {
			l.add(i);
		}
		
		System.out.println(l.get(1));
	}
	
}
